//
//  CityFileManager.m
//  MemberProject
//
//  Created by vincent luo on 15/7/9.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "CityFileManager.h"
#define kFileDirectory     @"/FileLog"
#define kCityLogDirectory      @"/CityFile"
#define kBankLogDirectory      @"/BankFile.plist"
#import "BuaatVolunteerServerSDK.h"

#define bankVersion @"bankVersion"

@implementation CityFileManager
+ (CityFileManager *)sharedManager
{
    static CityFileManager *sharedCityInfoManagerInstance = nil;
    
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedCityInfoManagerInstance = [[self alloc] init];
        [sharedCityInfoManagerInstance createDirectoty];
        //        [sharedUserInfoManagerInstance refreshUserInfo];
    });
    return sharedCityInfoManagerInstance;
}

/*
 存储日志路径
 */
- (NSString *)getFilePath:(NSString *)fileName
{
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [[array objectAtIndex:0] stringByAppendingString:fileName];
}


#pragma mark 创建文件目录
- (BOOL)createDirectoty

{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *logDirectory = [self getFilePath:kFileDirectory];
    
    return [fileManager createDirectoryAtPath:logDirectory
                  withIntermediateDirectories:YES
                                   attributes:nil
                                        error:nil];
}

#pragma mark 写入本地日志
-(void)writeLocalLog:(NSDictionary *)cityDic andFileName:(NSString *)fileName
{
    
    [self removeUserFile:fileName];

    
    NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithDictionary:cityDic];
    if (mDic[@"version"]==nil||[mDic[@"version"] isKindOfClass:[NSNull class]]) {
        [mDic setValue:@"" forKey:@"version"];
    }
    [mDic writeToFile:fileName atomically:YES];
    
}

#pragma mark 删除文件
-(void)removeUserFile:(NSString *)FileName
{
    // 文件存放目录
//    NSString *filePath = [self getFilePath:[NSString stringWithFormat:@"%@%@",kFileDirectory,kCityLogDirectory]];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    BOOL bRet = [fileMgr fileExistsAtPath:FileName];
    if (bRet) {
        //
        NSError *err;
        [fileMgr removeItemAtPath:FileName error:&err];
    }
}
#pragma mark 获取本地日志
-(NSArray *)getLocalLog:(NSInteger)style
{
    NSString *FileName = @"";
    if (style ==CityFileType) {
        FileName = kCityLogDirectory;
        NSString *path = [[CityFileManager sharedManager] getFilePath:kFileDirectory];
        NSString *localPath = [NSString stringWithFormat:@"%@%@",path,FileName];
        //    [self removeUserFile];
        
        //    NSArray *dataArr = [NSArray arrayWithContentsOfFile:localPath];
        NSDictionary *returnDic = [NSDictionary dictionaryWithContentsOfFile:localPath];
        
        NSArray *dataArr = returnDic[@"data"];
        
        return dataArr;
    }else if (style==BankFileType)
    {
        FileName = kBankLogDirectory;
        NSString *path = [[CityFileManager sharedManager] getFilePath:kFileDirectory];
        NSString *localPath = [NSString stringWithFormat:@"%@%@",path,FileName];
        
         NSArray *returnArr = [NSArray arrayWithContentsOfFile:localPath];
        return returnArr;
    }

    //    [self removeUserFile];
    return [NSArray new];
//    NSArray *dataArr = [NSArray arrayWithContentsOfFile:localPath];
//    NSDictionary *returnDic = [NSDictionary dictionaryWithContentsOfFile:localPath];
//
//    
//   
//    NSArray *dataArr = returnDic[@"data"];
////    NSString *version = returnDic[@"version"];
//    
//    return dataArr;
}

-(BOOL)isNeedToUpdate:(NSString *)version andType:(NSInteger)type
{
    NSString *FileName = @"";
    if (type ==CityFileType) {
        FileName = kCityLogDirectory;
        NSString *path = [[CityFileManager sharedManager] getFilePath:kFileDirectory];
        NSString *localPath = [NSString stringWithFormat:@"%@%@",path,FileName];
        NSDictionary *returnDic = [NSDictionary dictionaryWithContentsOfFile:localPath];
        if (returnDic) {
            NSString *dataVersion = returnDic[@"version"];
            if ([dataVersion isEqualToString:version]) {
                return NO;
            }else
            {
                return YES;
            }
        }else
        {
            return YES;
        }
        
        
    }else if (type==BankFileType)
    {
        NSString *bankV =[[NSUserDefaults standardUserDefaults]valueForKey:bankVersion];
        if (bankV!=nil&&[bankV isEqualToString:version]) {
            return NO;
            
        }else
        return YES;
    }else
    {
        return YES;
    }
    
    
    
    
    
}

-(void)getCityFile:(CSResultBlock)success andDefault:(CSVoidBlock)errorBlock
{
    [[BuaatVolunteerServerSDK sharedInstance]requestRegionRegionWithSuccess:^(NSHTTPURLResponse *response, id responseObject) {
        
//        NSArray *arr = responseObject;
//        [[CityFileManager sharedManager]writeLocalLog:arr];
//        NSDictionary *dic = responseObject;
        
        NSString *path = [self getFilePath:kFileDirectory];
        NSString *filePath =[NSString stringWithFormat:@"%@%@",path,kCityLogDirectory];
        
        NSDictionary *resultDic= responseObject[@"result"];
        [[CityFileManager sharedManager]writeLocalLog:resultDic andFileName:filePath];
        NSArray *dataArr = resultDic[@"data"];
        
        success (dataArr);
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        errorBlock();
    }];
    
    
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.requestSerializer=[AFJSONRequestSerializer serializer];
//    if (![[CityFileManager sharedManager]getLocalLog]) {
//        [manager POST:@"http://192.168.1.11:8080/v1/region/region" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            NSArray *arr = responseObject;
//            [[CityFileManager sharedManager]writeLocalLog:arr];
//            success (arr);
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            errorBlock();
//            
//        }];
//    }
}

-(void)getBankFile:(CSResultBlock)success andDefault:(CSVoidBlock)errorBlock
{
    [[BuaatVolunteerServerSDK sharedInstance]requestInsuranceGetBankListWithSuccess:^(NSHTTPURLResponse *response, id responseObject) {
        
        //        NSArray *arr = responseObject;
        //        [[CityFileManager sharedManager]writeLocalLog:arr];
        //        NSDictionary *dic = responseObject;
        
        
        NSString *path = [self getFilePath:kFileDirectory];
        NSString *filePath =[NSString stringWithFormat:@"%@%@",path,kBankLogDirectory];
        
        NSDictionary *resultDic= responseObject[@"result"];
        if (resultDic==nil||[resultDic isKindOfClass:[NSDictionary class]]) {
            
            NSArray *dataArr = resultDic[@"data"];
            if (dataArr) {
                [dataArr writeToFile:filePath atomically:YES];
            }
            
            NSString *bankV = resultDic[@"version"];
            [[NSUserDefaults standardUserDefaults]setValue:bankV forKey:bankVersion];
            NSArray *arr = [[CityFileManager sharedManager]getLocalLog:BankFileType];
                success(arr);
            
           
        }
            
        
        
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        errorBlock();
    }];
}

-(NSString *)getAreaNameFromCode:(NSString *)areaCode
{
    NSString *returnStr = @"";
    
    NSArray *cityFileArr = [[CityFileManager sharedManager]getLocalLog:CityFileType];
    NSString *proCode = [areaCode substringWithRange:NSMakeRange(0, 2)];
    NSString *cityCode = [areaCode substringWithRange:NSMakeRange(0, 4)];
    NSString *disCode = [areaCode substringWithRange:NSMakeRange(0, 6)];
    
    
    
    for (NSDictionary *dic in cityFileArr) {
        NSString *proCodeStr = dic[@"c"];
        if ([proCodeStr hasPrefix:proCode]) {
            
            returnStr = dic[@"n"];
            
            NSArray *cityArr = dic[@"child"];
            if (cityArr.count>0) {
                for (NSDictionary *cityDic in cityArr)
                {
                    NSString *cityCodeStr = cityDic[@"c"];
                    
                    
                    if ([cityCodeStr hasPrefix:cityCode])
                    {
                        
                        if ([cityDic.allKeys containsObject:@"child"]) {
                            NSArray *disArr = cityDic[@"child"];
                            if (disArr.count>0) {
                                //三级的
                                returnStr = [returnStr stringByAppendingString:cityDic[@"n"]];
                                
                                
                                for (NSDictionary *disDic in disArr) {
                                    NSString *disCodeStr = disDic[@"c"];
                                    if ([disCodeStr hasPrefix:disCode]) {
                                        returnStr = [returnStr stringByAppendingString:disDic[@"n"]];
                                        return returnStr;
                                        
                                        
                                    }
                                    
                                    
                                    
                                }
                            }else
                            {
                                //两级
                                returnStr = [returnStr stringByAppendingString:cityDic[@"n"]];
                                return returnStr;
                            }
                            
                            
                        }
                        
                        
                        
                        
                        
                        
                        
                    }
                    
                }
            }
            else
            {
                return returnStr;
                
            }
            
            
            
            
            
        }
        
        
    }
    
    
    return nil;
}



@end
